package com.af.community.smart.business

import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Bundle
import android.view.View
import android.webkit.*
import com.af.community.smart.base.BaseActivity
import com.af.community.smart.base.makeCall
import org.jetbrains.anko.browse
import org.jetbrains.anko.webView

class WebActivity : BaseActivity() {

    private lateinit var mWeb: WebView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mWeb = webView {
            overScrollMode = View.OVER_SCROLL_NEVER

            //支持javascript
            @Suppress("DEPRECATION")
            settings.javaScriptEnabled = true
            //设置可以支持缩放
            settings.setSupportZoom(true)
            //自适应屏幕
            settings.loadWithOverviewMode = true
            settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
            isHorizontalScrollBarEnabled = false

            //设置出现缩放工具
            settings.builtInZoomControls = true
            settings.displayZoomControls = false

            //设置是否使用缓存
            settings.setAppCacheEnabled(true)
            settings.domStorageEnabled = true

            webChromeClient = WebChromeClient()
            webViewClient = object : WebViewClient() {

                /*
                 * 当加载的网页需要重定向的时候就会回调这个函数告知我们应用程序是否需要接管控制网页加载，
                 * 如果应用程序接管，并且return true意味着主程序接管网页加载，如果返回false让webview自己处理
                 */
                @Suppress("DEPRECATION", "OverridingDeprecatedMember")
                override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                    return when {
                        "tel:" in url -> makeCall(url.replace("tel:", ""))
                        !url.startsWith("https://")
                                && !url.startsWith("http://") -> {
                            if (url.startsWith("weixin://wap/pay?")) browse(url)
                            true
                        }
                        url.endsWith(".apk") -> browse(url)
                        else -> {
                            view.loadUrl(url)
                            true
                        }
                    }
                }

                /*
                 * 在开始加载网页时会回调
                 */
                override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                    super.onPageStarted(view, url, favicon)
                    showLoading()
                }

                /*
                 * 在结束加载网页时会回调
                 */
                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    dismissLoading()
                }

                /*
                 * 当网页加载资源过程中发现SSL错误会调用此方法。
                 * 我们应用程序必须做出响应，是取消请求handler.cancel(),
                 * 还是继续请求handler.proceed(),
                 * 内核的默认行为是handler.cancel()
                 */
                override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
                    handler?.proceed() ?: super.onReceivedSslError(view, handler, error)
                }

            }
        }

        initTitle(intent.getStringExtra("title") ?: "详情")

        setWebData(intent.getStringExtra("type").orEmpty())
    }

    override fun doClick(v: View) {
        when (v.id) {
            R.id.iv_nav_back -> finish()
        }
    }

    private fun setWebData(type: String) {
        when (type) {
            "url" -> mWeb.loadUrl(intent.getStringExtra("content"))
            "handleList", "text" -> {
                val str = "<!doctype html><html>\n" +
                        "<meta charset=\"utf-8\">" +
                        "<style type=\"text/css\">" +
                        "body{ padding:0; margin:0; }\n" +
                        ".con{ width:95%; margin:0 auto; color:#666; padding:0.5em 0; overflow:hidden; display:block; font-size:0.92em; line-height:1.8em; }\n" +
                        ".con h1,h2,h3,h4,h5,h6{ font-size:1em; }\n" +
                        "img{ width:auto; max-width: 100% !important; height:auto !important; margin:0 auto; display:block; }\n" +
                        "*{ max-width:100% !important; }\n" +
                        "</style>\n" +
                        "<body style=\"padding:0; margin:0; \">" +
                        "<div class=\"con\">" +
                        intent.getStringExtra("content") +
                        "</div>" +
                        "</body>" +
                        "</html>"

                mWeb.loadDataWithBaseURL("", str, "text/html", "utf-8", "")
            }
        }
    }

    override fun onBackPressed() {
        if (mWeb.canGoBack()) mWeb.goBack()
        else super.onBackPressed()
    }

}
